/*
 *  src : 支持gulp 统配符
 *  lib: 输出仓库
 *  outputDir: 输出文件夹
 *  outputName: 输出文件名
 *
 * */
var fs = require("fs");
var http = require("http");
var iconv   = require('iconv-lite');
var query   = require('querystring');
var glob = require('glob');
var path = require('path');
var gutil = require('gulp-util');

function uploadFile(cfg, callback){

    var _cfg = cfg;

    // 收集参数
    var getServerInfo = function(){

        return {
            hostname: 'leonidapi.17usoft.com',
            port: 80,
            path: '/v1/leonid/static/uploadfile',
            method: 'PUT',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };
    }

    /*
     * file : 绝对路径 'D:/work/CQ-Partner/public/demo/test.js'
     * library: 输出仓库
     * outputDir: 输出文件夹
     * outputName: 输出文件名
     *
     * */
    var _upload = function(cfg, callback){
        //console.log(cfg.file, cfg.outputName, cfg.file,111111111111111)
        var _filePath = cfg.file,
            _lib      = cfg.lib,
            _fileName = cfg.outputName || cfg.file.split('\\').pop(),
            _dir      = cfg.outputDir,
            _callback = callback || function(){};

        var _dir = _dir.split('/').filter(function(ele){
            if(ele !== '') return  ele;
        });

        _dir.push(_fileName);

        var _fileData = fs.readFileSync(_filePath);

        _fileData = new Buffer(_fileData).toString('base64');

        var _data = {
            "userToken": "d45554083d97bd80561439aafebd137e",
            "bucketName": _lib,
            "key": _dir.join('/'),
            "pId": "57a99bc60a23ea2c52a7320f",
            "file": _fileData
        }

        var option = getServerInfo();

        var _req = http.request(option, function (respose) {

            /*
             这里是模拟客户端的，并不是服务端
             因为这个地方的数据是获取到这里的，而不是返回到浏览器的，
             所以这里设置cookie是不对的， 这里的res是访问的服务端返回到这里的，所以这个我们是
             读取服务端返回的res
             */

            var chunks = [];
            var size = 0;

            // 请求回流
            respose.on('data', function (chunk) {

                chunks.push(chunk)
                size += chunk.length;
            });

            // res 结束
            respose.on('end', function () {

                var buf = Buffer.concat(chunks, size);
                var str = iconv.decode(buf, 'utf-8');

                _callback(null, str, _dir.join('/'));
            });
        });

        _req.on('error', function (e) {
            console.log('problem with '+options.path+' request: ' + e.message);

            _callback(e, '');
        });

        _req.write(query.stringify(_data));

        _req.end();
    }

    /*
     * 获取参数启动上传
     * */
    if(typeof _cfg.src === 'string'){
        var aFiles = glob.sync(_cfg.src, {});
    }else if(_cfg.src.constructor.name === 'Array'){
        var aFiles = _cfg.src;
    }else{
        gutil.log(gutil.colors.red('Error: Src js String or Array!'));
    }

    if(!aFiles.length){
        gutil.log(gutil.colors.yellow('Warn: No file upload!'));
        callback();
        return;
    }

    var files = aFiles.map(function(file){
        return path.resolve(file)
    })

    var i = 0;

    ;void function(){

        var _that = arguments.callee;

        return _upload({
            file: files[i],
            lib: _cfg.lib,
            outputDir: _cfg.outputDir
        }, function(err, str){

            if(err) gutil.log(gutil.colors.red('Error upload: ' + err));

            gutil.log(gutil.colors.cyan((i+1-0) + '. >>... ' + files[i].split('\\').pop(), '...'+JSON.parse(str).msg));

            i++;

            if(!files[i]){
                callback();
                return gutil.log(gutil.colors.cyan('File upload complete!'));
            }else
                _that();

        });
    }();
}

module.exports = uploadFile;